package com.topway.dsmflex.util;


import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import org.apache.log4j.Logger;

import com.AppContext;

/**
 * 2013-05-06
 * 
 * @author liusy
 *
 */
public class ExpressionUtil {

	private  Logger log = Logger.getLogger(AppContext.class);
	   
	private  ScriptEngineManager manager = new ScriptEngineManager();
	
	private  ScriptEngine engine = manager.getEngineByName("JavaScript");
	
	private static ExpressionUtil eu = new ExpressionUtil();
	
	private String function =  "function liusyExpression(){  #LIUSY#   };  ";
	
	public static ExpressionUtil getExpressionUtil()
	{
		return eu;
	}
	
	
	public static String runExpre(String value,String expression)
	{
		return ExpressionUtil.getExpressionUtil().runExpression(value, expression);
	}
	
	public static String runExpre(String expression)
	{
		return ExpressionUtil.getExpressionUtil().runExpression(null, expression);
	}
	
	public String runExpression(String value,String expression)
	{
		String _value = "";
		try {
			engine.eval(getExpressionFunction(expression));
			Invocable inv = (Invocable) engine;
			_value= String.valueOf(inv.invokeFunction("liusyExpression"));
		} catch (ScriptException e) {
			log.error(e.getMessage()+"表达式错["+expression+"]误 忽略");
		} catch (NoSuchMethodException e) {
			log.error(e.getMessage()+"表达式错["+expression+"]误 忽略");
		}
		
		return ! _value.equals("null")?_value:value;

	}
	
	private String getExpressionFunction(String expression)
	{
		return function.replace("#LIUSY#", expression);
	}
	
	
//	var stationname={SUBSTATIONNAME};
//	if(stationname.indexOf('季华变电站')!=-1)
//	return '这是季华变电站';
//	else return '不是季华变电站';
	
	public static void main(String[] args) throws ScriptException, NoSuchMethodException {
		ScriptEngineManager manager = new ScriptEngineManager();
		ScriptEngine engine = manager.getEngineByName("JavaScript");
		//engine.eval("print ('Hello World'.replace('e','aa'))");
		String aa = "Hello World";
		Object obj = engine.eval("'"+aa+"'.substr(1,3)");
		//System.out.println(obj);
		String regex = "function regex(regStr,v){  var reg = regStr;  return reg.test(v); };  function chkChinese(v){ return regex(/^[\u0391-\uFFE5]+$/,v);  };";
		String script = " var i =1; function test(){  for(var a =1;a<3;a++){print('dfaa');}; var i =1; if(i==1)return chkChinese('df'); else return 'this is test js in java';}";
		//System.out.println(ExpressionUtil.runExpre("aaa", script));
		
		
		
		
		String abc = "var stationname='ddd季华变电站'; if(stationname.indexOf('季华变电站')!=-1) return '这是季华变电站''\\''; else return 'fd'";
		System.out.println(ExpressionUtil.runExpre("aaa", abc));
		//对像测试
//	    File file = new File(Consts.DATAFILE);   
//	    engine.put("f", file);   
//	    engine.eval("println('Total Space:'+f.getTotalSpace())");   
//	    engine.eval("println('Path:'+f.getPath())");   
//		System.out.println(obj);
		
	}
   

}
